import * as http from "http";
import * as url  from "url";

import {FinchLogger_Color} from "finch-log";

import {responseWare}       from "../responseWare";
import {Finch}              from "./class_Finch";
import {checkStaticFile}    from "./function_checkStaticFile";
import {processMiddlewares} from "./function_processMiddlewares";
import {parsedRequest}      from "./interface";

/**
 * 创建请求函数，Node原生API中，需要一个 (incomingMessage,ServerResponse)=>{} 函数来处理请求和返回，此方法生成这样一个函数
 * @param finchApp finch app
 * @return 匿名函数 (incomingMessage,ServerResponse)=>{}
 */
function createRequestListener(finchApp: Finch)
{
    return function (req: parsedRequest, res: http.ServerResponse)
    {

        // req.setEncoding("utf8");
        let decodeUrl = url.parse(decodeURIComponent(req.url), true);

        //解析url路径名
        let pathname = decodeUrl.pathname;
        //解析url请求
        let theQuery = decodeUrl.query;

        let staticFilePath = checkStaticFile(finchApp, pathname);

        req.query    = theQuery;
        req.pathName = pathname;

        function log(message: string, color: FinchLogger_Color)
        {
            if (finchApp.Logger)
            {
                finchApp.Logger.log(message, color);
            }
            else
            {
                console.log(message)
            }
        }


        if (finchApp.Handles.hasOwnProperty(pathname))
        {

            log(`HANDLE: ${pathname}`, FinchLogger_Color.green);
            try
            {
                processMiddlewares(req, res, finchApp.Handles[pathname]);
            } catch (e)
            {
                log(`${e.message}\r\n${e.stack}`, FinchLogger_Color.red);
            }
            return;
        }

        if (staticFilePath)
        {
            log(`HANDLE: STATIC ${pathname}`, FinchLogger_Color.green);
            responseWare.rStaticFile(res, staticFilePath);
            return;
        }

        log(`NO_HANDLE! ${pathname}`, FinchLogger_Color.red);

        responseWare.r404(res);
    }
}

export {createRequestListener}